package cn.yuanqiao.archive.singleSignOn.util;

import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Component
public class SymmetricEncryption {

   public String Encrypt(String plaintext,String secretKey){
       String encryptedText="";
       try {

           // Generate Key
           SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES");

           // Create Cipher
           Cipher cipher = Cipher.getInstance("AES");

           // Encrypt
           cipher.init(Cipher.ENCRYPT_MODE, key);
           byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
            encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
       }catch (Exception ex){
           ex.printStackTrace();
       }
           return encryptedText;
   }

    public String Decrypt(String encryptedText,String secretKey){
        String decryptedText="";
        try {

            // Generate Key
            SecretKey key = new SecretKeySpec(secretKey.getBytes(), "AES");

            // Create Cipher
            Cipher cipher = Cipher.getInstance("AES");

            // Encrypt
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
             decryptedText = new String(decryptedBytes);
           // return decryptedText;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return decryptedText;
    }






    //
}
